package com.vf.admin.client.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dto.AppUserDressupDto;
import com.vf.admin.client.service.*;
import com.vf.admin.client.tx.utils.TxIm;
import com.vf.admin.client.tx.vo.UserShiZhi;
import com.vf.admin.client.tx.vo.userSignVo;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.entity.AppHeadwear;
import com.vf.admin.miaodong.entity.AppMounts;
import com.vf.admin.miaodong.entity.AppUser;
import com.vf.admin.miaodong.entity.AppUserDressup;
import com.vf.admin.utils.StringEx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.vf.admin.utils.StringEx.isNull;
import static com.vf.admin.utils.TimeUtils.daojishi;

/**
 * 商城（坐骑头饰）
 * <p>
 * 商城头像框（包含购买 添加接口）
 * 商城坐骑列表（包含购买 添加接口）
 * 我的装扮
 * 提现功能（包含金额列表）
 */

@CrossOrigin
@Controller
@RequestMapping("/app/shop")
public class AppShopController extends ClientBaseController {

    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppMountsService appMountsService;
    @Autowired
    AppHeadwearService appHeadwearService;
    @Autowired
    AppUserDressupService appUserDressupService;
    @Autowired
    AppDressuprecordService appDressuprecordService;

    /**
     * 获取商城售卖的坐骑
     *
     * @param pageno 第几页
     * @return
     */
    @RequestMapping(value = "/getMounts")
    @ResponseBody
    public Result getMounts(Integer pageno) {
        if (StringEx.isNull(pageno)) {
            return this.errorJSON("页码不能为空");
        }
        SplitPageBean splitPageBean = new SplitPageBean(pageno, 12);
        List<AppMounts> list = appMountsService.shopList(splitPageBean);
        return sucessPage(list, splitPageBean.getNextPageNo());
    }

    /**
     * 获取商城售卖的头饰
     *
     * @param pageno 第几页
     * @return
     */
    @RequestMapping(value = "/getHeadwear")
    @ResponseBody
    public Result getHeadwear(Integer pageno) {
        if (StringEx.isNull(pageno)) {
            return this.errorJSON("页码不能为空");
        }
        SplitPageBean splitPageBean = new SplitPageBean(pageno, 12);
        List<AppHeadwear> list = appHeadwearService.shopList(splitPageBean);
        return sucessPage(list, splitPageBean.getNextPageNo());
    }

    /**
     * 获取自己的头饰和坐骑
     *
     * @param type 1坐骑  2头饰
     * @return
     */
    @RequestMapping(value = "/getMyHeadwear")
    @ResponseBody
    public Result getMyHeadwear(Integer type) {
        if (StringEx.isNull(type)) {
            return this.errorJSON("类型错误");
        }
        Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        List<AppUserDressup> list = appUserDressupService.selectMountsByUserid(userId, type);
        List<AppUserDressupDto> appUserDressupDtos = new ArrayList<>();
        if (list != null && list.size() > 0) {
            for (AppUserDressup appUserDressup : list) {
                AppUserDressupDto appUserDressupDto = new AppUserDressupDto();
                appUserDressupDto.setId(appUserDressup.getId());
                appUserDressupDto.setMountsid(appUserDressup.getMountsid());//坐骑id
                appUserDressupDto.setState(appUserDressup.getState());//状态 1、默认  2、不默认 默认为：2、不默认
                appUserDressupDto.setBuyingtime(appUserDressup.getBuyingtime());
                appUserDressupDto.setDay(appUserDressup.getDay());
                appUserDressupDto.setOvertime(appUserDressup.getOvertime());
                appUserDressupDto.setPic(appUserDressup.getPic());
                appUserDressupDto.setNick(appUserDressup.getNick());
                appUserDressupDto.setPhone(appUserDressup.getPhone());
                appUserDressupDto.setGoodpic(appUserDressup.getGoodpic());
                appUserDressupDto.setGoodname(appUserDressup.getGoodname());
                appUserDressupDto.setShengyutime(daojishi(appUserDressup.getOvertime()));
                appUserDressupDtos.add(appUserDressupDto);
            }
        }
        Map<String, Object> mm = new HashMap<>(16);
        mm.put("list", appUserDressupDtos);
        return sucessJSON(mm);
    }

    /**
     * 默认坐骑或者头饰
     *
     * @param dressupid //坐骑或头饰id
     * @param type      //1坐骑  2头饰
     * @return
     */
    @RequestMapping(value = "/dressupDefault")
    @ResponseBody
    public Result dressupDefault(Integer dressupid, Integer type) {
        try {
            if (StringEx.isNull(dressupid)) {
                return this.errorJSON("ID不能为空");
            }
            if (StringEx.isNull(type)) {
                return this.errorJSON("类型错误");
            }
            Integer userid = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            if (userid == null || userid == 0) {
                return errorJSON("请先登录！");
            }
            AppUser user = appUserService.get(userid);
            AppUserDressup userDressup = appUserDressupService.get(dressupid);
            List<AppUserDressup> appUserDressups = appUserDressupService.selectMountsByUserid(userid, type);
            //坐骑
            if (type == 1) {
                if (userDressup == null) {
                    return errorJSON("坐骑不存在或已过期");
                }
                if (userDressup.getType() != 1) {
                    return errorJSON("坐骑不存在或已过期");
                }
                if (appUserDressups.size() != 0) {
                    for (AppUserDressup dressup : appUserDressups) {
                        Integer id1 = dressup.getId();
                        AppUserDressup byId1 = appUserDressupService.get(id1);
                        byId1.setState(2);
                        appUserDressupService.save(byId1);
                    }
                }
                if (userDressup.getState() == 1) {
                    userDressup.setState(2);
                } else if (userDressup.getState() == 2) {
                    userDressup.setState(1);
                }
                appUserDressupService.save(userDressup);
                return sucessJSON("成功");
            } else if (type == 2) {//头饰
                if (userDressup == null) {
                    return errorJSON("头饰不存在或已过期");
                }
                if (userDressup.getType() != 2) {
                    return errorJSON("头饰不存在或已过期");
                }
                if (appUserDressups.size() != 0) {
                    for (AppUserDressup dressup : appUserDressups) {
                        Integer id = dressup.getId();
                        AppUserDressup byId1 = appUserDressupService.get(id);
                        byId1.setState(2);
                        appUserDressupService.save(byId1);
                    }
//                    if (userDressup.getState() == 1) {
//                        userDressup.setState(2);
//                    } else if (userDressup.getState() == 2) {
                        userDressup.setState(1);
//                    }
                    appUserDressupService.save(userDressup);

                    //获取用户腾讯方最新的数据
                    String re = TxIm.portraitGget(user.getTengxuncode());
                    Integer headHalo = 0;
                    Integer charmNum = 0;
                    Integer isVip = 0;
                    if (!isNull(re)) {
                        JSONObject jsonObject1 = JSON.parseObject(re);
                        headHalo = jsonObject1.getInteger("headHalo");
                        charmNum = jsonObject1.getInteger("charmNum");
                        isVip = jsonObject1.getInteger("isVip");
                    }
                    //重新设置资料
                    userSignVo vo1 = new userSignVo();
                    vo1.setId(user.getId());
                    vo1.setCharmNum(charmNum);
//                    if (userDressup.getState() == 1) {
//                        userDressup.setState(2);
//                        vo1.setHeadWear("");
//                    } else if (userDressup.getState() == 2) {
                        userDressup.setState(1);
                        vo1.setHeadWear(userDressup.getGoodpic());
//                    }
                    vo1.setHeadHalo(headHalo);
                    vo1.setNobleid(user.getNobleid());
                    vo1.setStatus(user.getStatus());
                    vo1.setIsVip(isVip);
                    net.sf.json.JSONObject obj1 = net.sf.json.JSONObject.fromObject(vo1);
                    UserShiZhi shiZhi = new UserShiZhi();
                    shiZhi.setUserSign(obj1.toString());
                    shiZhi.setTengxuncode(user.getTengxuncode() + "");
                    TxIm.portraitSet(shiZhi);
                    return sucessJSON("成功");
                } else {
                    return errorJSON("失败");
                }
            } else {
                return errorJSON("失败");
            }
        } catch (Exception r) {
            return errorJSON("网络繁忙，请稍后重试");
        }
    }

    /**
     * 购买坐骑和头饰
     *
     * @param goodid 物品id
     * @param type   1坐骑  2头饰
     * @return
     */
    @RequestMapping(value = "/buyMountsOrHeadwear")
    @ResponseBody
    public Result buyMountsOrHeadwear(Integer goodid, Integer type) {
        if (StringEx.isNull(goodid)) {
            return this.errorJSON("ID不能为空");
        }
        if (StringEx.isNull(type)) {
            return this.errorJSON("类型不能为空");
        }
        Integer userid = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
        AppUser user = appUserService.get(userid);
        if (type == 1) {
            //坐骑
            AppMounts mounts = appMountsService.get(goodid);
            if (mounts == null) {
                return errorJSON("坐骑不存在");
            }
            //调用购买坐骑
            boolean flag = appUserDressupService.shopZuoqi(user, mounts);
            if (flag) {
                return sucessJSON("成功");

            } else {
                return errorJSON("网络繁忙，请稍后重试");
            }
        } else if (type == 2) {
            //头饰
            AppHeadwear headwear = appHeadwearService.get(goodid);
            if (headwear == null) {
                return errorJSON("头饰不存在");
            }
            //调用购买头饰
            boolean flas = appUserDressupService.shopToushi(user, headwear);
            if (flas) {
                return sucessJSON("成功");
            } else {
                return errorJSON("头饰购买失败");
            }
        } else {
            return errorJSON("类型错误");
        }
    }


    /**
     * 取消默认
     */
    @RequestMapping(value = "/cancelDefault")
    @ResponseBody
    public Result cancelDefault(Integer type) {
        try {
            if (StringEx.isNull(type)) {
                return this.errorJSON("类型错误");
            }
            Integer userid = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userid);
            if ("1".equals(type)) {//坐骑
                List<AppUserDressup> appUserDressups = appUserDressupService.selectMountsByUserid(userid, type);
                if (appUserDressups.size() != 0) {
                    for (AppUserDressup dressup : appUserDressups) {
                        Integer id = dressup.getId();
                        AppUserDressup byId1 = appUserDressupService.get(id);
                        byId1.setState(2);
                        appUserDressupService.save(byId1);
                    }
                }
                return sucessJSON("成功");
            } else {//头饰
                List<AppUserDressup> appUserDressups = appUserDressupService.selectMountsByUserid(userid, type);
                if (appUserDressups.size() != 0) {
                    for (AppUserDressup dressup : appUserDressups) {
                        Integer id = dressup.getId();
                        AppUserDressup byId1 = appUserDressupService.get(id);
                        byId1.setState(2);
                        appUserDressupService.save(byId1);
                    }
                }
                //获取用户腾讯方最新的数据
                String re = TxIm.portraitGget(user.getTengxuncode());
                Integer headHalo = 0;
                Integer charmNum = 0;
                Integer isVip = 0;
                if (!isNull(re)) {
                    JSONObject jsonObject1 = JSON.parseObject(re);
                    headHalo = jsonObject1.getInteger("headHalo");
                    charmNum = jsonObject1.getInteger("charmNum");
                    isVip = jsonObject1.getInteger("isVip");
                }
                //重新设置资料
                userSignVo vo1 = new userSignVo();
                vo1.setId(user.getId());
                vo1.setCharmNum(charmNum);
                vo1.setHeadWear("");
                vo1.setHeadHalo(headHalo);
                vo1.setNobleid(user.getNobleid());
                vo1.setIsVip(isVip);
                net.sf.json.JSONObject obj1 = net.sf.json.JSONObject.fromObject(vo1);
                UserShiZhi shiZhi = new UserShiZhi();
                shiZhi.setUserSign(obj1.toString());
                shiZhi.setTengxuncode(user.getTengxuncode() + "");
                TxIm.portraitSet(shiZhi);
                return sucessJSON("成功");
            }
        } catch (Exception e) {
            return errorJSON("网络繁忙，请稍后重试");
        }
    }


}
